package com.minhang.utils;/**
 * Created by wucha on 2020/3/12.
 */

import com.minhang.utils.result.Result;
import com.minhang.utils.result.ResultGenerator;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


/**
 * 文件上传工具类
 *
 * @author
 */
@Slf4j
@Component
public class FileUtil {

    @Value("${file.url}")
    private String path;


    /**
     * 文件上传
     *
     * @param file（UID文件名）
     * @return
     */
    public Result uploadFile(MultipartFile file, String folder) {

        if (file == null) {
            return ResultGenerator.genFailResult("文件为空");
        }
        // 得到文件名
        String filename = file.getOriginalFilename();
        // 文件后缀名
        String prefix = filename.substring(filename.lastIndexOf(".") + 1);
        //得到除去后缀的名字
        String qian = filename.substring(0, filename.lastIndexOf("."));
        //自定义文件名
        String destFileName = UUID.randomUUID().toString().replace("-", "") + "." + prefix;

        File fileUrl = new File(path + folder);
        if (!fileUrl.exists()) {
            fileUrl.mkdirs();
        }
        File destFile = new File(fileUrl, destFileName);

        try {
            Map<String, String> response = new HashMap<>();
            file.transferTo(destFile);
            response.put("filePath", path + folder + destFileName);
            response.put("fileName", qian);
            log.info("文件上传成功：路径={}", destFile);
            return ResultGenerator.genSuccessResultFilePath(response, (path + folder + destFileName));
        } catch (IOException e) {
            e.printStackTrace();
            log.info("文件上传失败", e);
            return ResultGenerator.genFailResult("上传失败");
        }
    }

    /**
     * 文件上传（原文件名）
     *
     * @param file
     * @param folder
     * @return
     */
    public Result upload(MultipartFile file, String folder) {
        if (file == null) {
            return ResultGenerator.genFailResult("文件为空");
        }
        // 得到文件名
        String filename = file.getOriginalFilename();
        // 文件后缀名
        //得到除去后缀的名字
        String qian = filename.substring(0, filename.lastIndexOf("."));

        File fileUrl = new File(path + folder);
        if (!fileUrl.exists()) {
            fileUrl.mkdirs();
        }
        File destFile = new File(fileUrl, filename);
        try {
            Map<String, String> response = new HashMap<>();
            file.transferTo(destFile);
            response.put("filePath", path + folder + filename);
            response.put("fileName", qian);
            log.info("文件上传成功：路径={}", destFile);
            return ResultGenerator.genSuccessResultFilePath(response, (path + folder + filename));
        } catch (IOException e) {
            e.printStackTrace();
            log.info("文件上传失败", e);
            return ResultGenerator.genFailResult("上传失败");
        }
    }

    /**
     * 把图片生成base64
     *
     * @param file
     * @return
     */
    public Map<String, String> getBase64(MultipartFile file, String folder) {
        if (file == null) {
            return null;
        }
        //自定义文件名
        String destFileName = UUID.randomUUID().toString().replace("-", "");
        File fileUrl = new File(path + folder);
        if (!fileUrl.exists()) {
            fileUrl.mkdirs();
        }
        try {
            Thumbnails.of(file.getInputStream()).scale(0.8f).outputFormat("jpg").outputQuality(0.5).toFile(path + folder + destFileName);
            File file1 = new File(path + folder + destFileName+".jpg");
            FileInputStream inputStream = new FileInputStream(file1);
            byte[] buffer = new byte[(int) file1.length()];
            inputStream.read(buffer);
            inputStream.close();
            // 转换为base64编码格式
            String base64 = new sun.misc.BASE64Encoder().encode(buffer);
            // 上面方法中获得的base64编码中，包含有换行符，统一全部替换掉
            base64 = base64.replaceAll("[\\s*\t\n\r]", "");
            Map<String, String> map = new HashMap<>();
            map.put("file", (path + folder + destFileName+".jpg"));
            map.put("base64", "data:image/jpg;base64," + base64);
            return map;
        } catch (IOException e) {
            e.printStackTrace();
            log.info("文件上传失败", e);
            return null;
        }
    }


    /**
     * 把图片生成base64
     *
     * @return
     */
    public String getBase64(String folder) {
        try {
            if (folder != null) {
                File file = new File(folder);
                FileInputStream inputStream = new FileInputStream(file);
                byte[] buffer = new byte[(int) file.length()];
                inputStream.read(buffer);
                inputStream.close();
                // 转换为base64编码格式
                String base64 = new sun.misc.BASE64Encoder().encode(buffer);
                // 文件后缀名
                String prefix = folder.substring(folder.lastIndexOf(".") + 1);
                // 上面方法中获得的base64编码中，包含有换行符，统一全部替换掉
                base64 = base64.replaceAll("[\\s*\t\n\r]", "");
                return "data:image/" + prefix + ";base64," + base64;
            }
            return null;

        } catch (IOException e) {
            e.printStackTrace();
            log.info("文件上传失败", e);
            return null;
        }
    }


}
